package sdc.com.petscalendar.fragments;

import java.io.File;
import java.io.FileOutputStream;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;

import sdc.com.petscalendar.MainActivity;
import sdc.com.petscalendar.R;
import sdc.com.petscalendar.objects.Veto;
import sdc.com.petscalendar.utils.Statics;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class VetoEditFragment extends BaseFragment implements
		View.OnClickListener {
	private ImageView mIvAvatar;
	private View mBtnTakePicture, mBtnExport;
	private EditText mEdtName, mEdtAdress, mEdtZip, mEdtCity, mEdtTel,
			mEdtEmail;
	public static String JPEG_FILE_PREFIX = "VETO_PT";
	private boolean saved = false;
	public static int RQ_GET_VETO_PICTURE = 1000;
	private Bitmap mImageBitmap;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (mView == null) {
			mView = inflater.inflate(R.layout.fragment_veto_edit, container,
					false);
		}
		return mView;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		initComponents();
		addListeners();
	}

	protected void initComponents() {
		mBtnTakePicture = getView().findViewById(R.id.btn_take_picture);
		mBtnExport = getView().findViewById(R.id.btn_export);
		mIvAvatar = (ImageView) getView().findViewById(R.id.iv_avatar);

		mEdtAdress = (EditText) getView().findViewById(R.id.edt_address);
		mEdtCity = (EditText) getView().findViewById(R.id.edt_city);
		mEdtEmail = (EditText) getView().findViewById(R.id.edt_email);
		mEdtName = (EditText) getView().findViewById(R.id.edt_name);
		mEdtTel = (EditText) getView().findViewById(R.id.edt_tel);
		mEdtZip = (EditText) getView().findViewById(R.id.edt_zip);

		if (Statics.sVeto.getAvatar() != null
				&& Statics.sVeto.getAvatar().length() > 0) {
			Log.d("FILE", Statics.sVeto.getAvatar());
			if (new File(Statics.sVeto.getAvatar()).exists()) {
				DisplayImageOptions options = new DisplayImageOptions.Builder()
						.showStubImage(R.drawable.default_avatar)
						.showImageForEmptyUri(R.drawable.default_avatar)
						.showImageOnFail(R.drawable.default_avatar)
						.resetViewBeforeLoading()
						.cacheInMemory()
						.bitmapConfig(Bitmap.Config.ARGB_8888) // default
						.displayer(new SimpleBitmapDisplayer()) // default
						.build();
				ImageLoader.getInstance().displayImage("file:///"+
						Statics.sVeto.getAvatar(), mIvAvatar, options);
				
			}
		}

		((MainActivity) getActivity()).showBtnNavLeft(true);

		if (Statics.sVeto != null) {
			if (Statics.sVeto.getAvatar() != null
					&& Statics.sVeto.getAvatar().length() > 0) {
				Bitmap bm = BitmapFactory.decodeFile(Statics.sVeto.getAvatar());
				mIvAvatar.setImageBitmap(bm);
			}
			mEdtName.setText(Statics.sVeto.getName());
			mEdtAdress.setText(Statics.sVeto.getAddress());
			mEdtCity.setText(Statics.sVeto.getCity());
			mEdtEmail.setText(Statics.sVeto.getEmail());
			mEdtTel.setText(Statics.sVeto.getPhone());
			mEdtZip.setText(Statics.sVeto.getZip());
		}

		((MainActivity) getActivity())
				.setBtnNavLeftOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						if (checkFields()) {
							if (Statics.sVeto == null) {
								Statics.sVeto = new Veto();
								Statics.sVeto.setId(0);
							}
							Statics.sVeto
									.setName(mEdtName.getText().toString());
							Statics.sVeto
									.setCity(mEdtCity.getText().toString());
							Statics.sVeto.setEmail(mEdtEmail.getText()
									.toString());
							Statics.sVeto
									.setPhone(mEdtTel.getText().toString());
							Statics.sVeto.setZip(mEdtZip.getText().toString());
							saved = true;
							new SaveFileTask().execute();
						}
					}
				});
	}

	protected void addListeners() {
		mBtnTakePicture.setOnClickListener(this);
		mBtnExport.setOnClickListener(this);
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_export:

			break;
		case R.id.btn_take_picture:
			dispatchTakePictureIntent();
			break;

		default:
			break;
		}
	}

	@Override
	public void onDestroyView() {
		((MainActivity) getActivity()).showBtnNavLeft(false);
		if (!saved) {
			Statics.sVeto = null;
		}
		Statics.sRequestCode = 0;
		super.onDestroyView();
		if (mImageBitmap != null) {
			mImageBitmap.recycle();
		}
	}

	private Toast toast;

	boolean checkFields() {
		if (mEdtName.getText().toString().trim().length() == 0) {
			toast = Toast.makeText(getActivity(), "Name required!",
					Toast.LENGTH_LONG);
			toast.show();
			return false;
		}
		if (mEdtAdress.getText().toString().trim().length() == 0) {
			toast = Toast.makeText(getActivity(), "Adress required!",
					Toast.LENGTH_LONG);
			toast.show();
			return false;
		}
		if (mEdtZip.getText().toString().trim().length() == 0) {
			toast = Toast.makeText(getActivity(), "Zipcode required!",
					Toast.LENGTH_LONG);
			toast.show();
			return false;
		}
		if (mEdtCity.getText().toString().trim().length() == 0) {
			toast = Toast.makeText(getActivity(), "City required!",
					Toast.LENGTH_LONG);
			toast.show();
			return false;
		}
		if (mEdtTel.getText().toString().trim().length() == 0) {
			if (mEdtEmail.getText().toString().trim().length() == 0) {
				toast = Toast.makeText(getActivity(), "Tel required!",
						Toast.LENGTH_LONG);
				toast.show();
				return false;
			} else if (!mEdtEmail.getText().toString()
					.matches("[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+")
					&& (!mEdtEmail
							.getText()
							.toString()
							.matches(
									"[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+\\.+[a-z]+"))
					&& (!mEdtEmail
							.getText()
							.toString()
							.matches(
									"[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+\\.+[a-z]+\\.+[a-z]+"))) {
				toast = Toast.makeText(getActivity(), "Invaild email!",
						Toast.LENGTH_LONG);
				toast.show();
				return false;
			} else {
				return true;
			}
		}
		if (mEdtEmail.getText().toString().length() > 0
				&& (!mEdtEmail.getText().toString()
						.matches("[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+"))
				&& (!mEdtEmail.getText().toString()
						.matches("[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+\\.+[a-z]+"))
				&& (!mEdtEmail
						.getText()
						.toString()
						.matches(
								"[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+\\.+[a-z]+\\.+[a-z]+"))) {
			toast = Toast.makeText(getActivity(), "Invaild email!",
					Toast.LENGTH_LONG);
			toast.show();
			return false;
		}

		return true;
	}

	private void dispatchTakePictureIntent() {
		Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		getActivity().startActivityForResult(takePictureIntent,
				RQ_GET_VETO_PICTURE);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == RQ_GET_VETO_PICTURE
				&& resultCode == Activity.RESULT_OK) {
			Bundle extras = data.getExtras();
			mImageBitmap = (Bitmap) extras.get("data");
			mIvAvatar.setImageBitmap(mImageBitmap);
			super.onActivityResult(requestCode, resultCode, data);
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		if (Statics.sRequestCode != 0) {
			onActivityResult(Statics.sRequestCode, Statics.sResultCode,
					Statics.sData);
		}
	}

	private File saveImage(String name) {
		try {
			// Create an image file name
			File storageDir = new File(Environment
					.getExternalStorageDirectory().getPath() + "/petapp_data");

			if (!storageDir.exists()) {
				storageDir.mkdir();
			}
			storageDir = new File(storageDir.getPath() + "/photo");
			if (!storageDir.exists()) {
				storageDir.mkdir();
			}
			File imageFile = new File(storageDir.getPath() + "/" + name);

			if (imageFile.exists()) {
				imageFile.delete();
			}
			imageFile.createNewFile();
			mImageBitmap.compress(CompressFormat.JPEG, 100,
					new FileOutputStream(imageFile));
			return imageFile;
		} catch (Exception e) {
			return null;
		}
	}

	private String getPhotoStorageDir() {
		return Environment.getExternalStorageDirectory().getPath()
				+ "/petapp_data/photo/";
		
	}

	private class SaveFileTask extends AsyncTask<Void, Void, File> {
		ProgressDialog mDialog;

		@Override
		protected File doInBackground(Void... params) {
			if (mImageBitmap != null)
				return saveImage("veto_" + Statics.sVeto.getId());
			return null;
		}

		@Override
		protected void onPostExecute(File result) {
			mDialog.dismiss();
			if (result != null) {
				Statics.sVeto.setAvatar(result.getPath());

			} else {
				// Toast.makeText(getActivity(), "Save fail",
				// Toast.LENGTH_LONG);
			}
			getActivity().onBackPressed();
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			mDialog = new ProgressDialog(getActivity());
			mDialog.setMessage("Sauvetage...");
			mDialog.setCancelable(false);
			mDialog.show();
			super.onPreExecute();
		}

	}
}
